package com.hxzy.framework.web.security.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.hxzy.common.constant.CacheConstants;
import com.hxzy.common.constant.Constants;
import com.hxzy.common.core.domain.AjaxResult;
import com.hxzy.common.core.domain.model.LoginUser;
import com.hxzy.common.core.redis.RedisCache;
import com.hxzy.common.enums.HttpStatus;
import com.hxzy.common.utils.ServletUtils;
import com.hxzy.manager.AsyncManager;
import com.hxzy.manager.factory.AsyncFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 登出操作，从本地线程中，取不到用户信息的
 * spring security点击用户退出操作
 *  删除redis中的令牌
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Autowired
    private RedisCache redisCache;

    /**
     * 请求头参数
     */
    @Value(value = "${token.header}")
    private String  header;

    private final String bearer="Bearer";

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //从请求头获取数据
        String jwtToken=request.getHeader(header);
        if(StrUtil.isNotBlank(jwtToken)) {
            //解析jwt
            if (jwtToken.startsWith(bearer)) {
                jwtToken = jwtToken.substring(bearer.length() + 1).trim();
            }
            //jwt解密
            JWT jwt = JWTUtil.parseToken(jwtToken);
            //4、取值
            String uuid = jwt.getPayload("uuid").toString();
            //5、拼接rediskey
            String redisKey = CacheConstants.LOGIN_TOKEN_KEY + uuid;

          Object  obj=this.redisCache.getCacheObject(redisKey);
          if(Objects.nonNull(obj)){
              LoginUser loginUser= (LoginUser) obj;
              this.redisCache.deleteObject(redisKey);
              // 记录用户退出日志
              AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginUser.getUsername(), Constants.LOGOUT, "退出成功"));

          }

        }

        //输出json
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));

    }
}
